#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>

//#define USING_CONNECT

static int sock;
static struct sockaddr_in server_addr;

void *thread1(void *arg)
{
	int restul;
	int count;
	char buffer[100];
	
	count = 0;
	while(1)
	{
		count++;
		snprintf(buffer, sizeof(buffer), "udp client test,%d\r\n", count);
#ifdef USING_CONNECT
		if(write(sock, buffer, strlen(buffer)) == -1)
		{
			close(sock);
			perror("write");
			exit(-1);
		}
#else
		if(sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
		{
			close(sock);
			perror("sendto");
			exit(-1);
		}
#endif
		sleep(1);
	}
}

int main(int argv, char *argc[])
{
	int restul;
	pthread_t tid;
#ifndef USING_CONNECT
	socklen_t addr_lenght;
	struct sockaddr_in peer_addr;
#endif
	char buffer[100];
	char *ip = "192.168.2.62";
	char *port = "43200";
	
	if(argv > 1)
		ip = argc[1];
	if(argv > 2)
		port = argc[2];
	
	//创建套接字
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock == -1)
	{
		perror("socket");
		return -1;
	}
	//缓存服务器IP和端口
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(port));
	server_addr.sin_addr.s_addr = inet_addr(ip);
	printf("IP %s; port %d\r\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));
#ifdef USING_CONNECT
	//设置服务器IP和端口
	if(connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
	{
		close(sock);
		perror("connect");
		return -1;
	}
#endif

	//创建线程
	restul = pthread_create(&tid, NULL, thread1, "this thread1");
	if(restul != 0)
	{
		close(sock);
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	//脱离线程
	restul = pthread_detach(tid);
	if(restul != 0)
	{
		close(sock);
		printf("pthread_detach: error code %d\r\n", restul);
		return -1;
	}
	
	while(1)
	{
		//读服务器发送过来的数据
#ifdef USING_CONNECT
		memset(buffer, 0, sizeof(buffer));
		if(read(sock, buffer, sizeof(buffer)-1) == -1)
		{
			close(sock);
			perror("read");
			return -1;
		}
#else
		memset(buffer, 0, sizeof(buffer));
		addr_lenght = sizeof(peer_addr);
		if(recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer_addr, &addr_lenght) == -1)
		{
			close(sock);
			perror("recvfrom");
			return -1;
		}
#endif
		printf("%s", buffer);
		fflush(stdout);
	}
}
